"""
Case Type   : create table as
Case Name   : 源表为分区表，执行create table as
Create At   : 2024/4/16
Owner       : @li-xin12345
Description :
    1、创建用户
    2、建源表
    3、收回用户在当前模式的create权限
    4、赋予用户源表的所有权限
    5、以新建用户身份进入当前模式，执行create table as
    6、清理环境
Expect      :
    1、成功
    2、成功
    3、成功
    4、成功
    5、报错权限受限
    6、成功
History     :
"""

import os
import unittest

from yat.test import Node
from yat.test import macro

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class CreateTableAsTest(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.pri_user = Node('PrimaryDbUser')
        self.constant = Constant()
        self.tb_name = ['t_cta_0047_01', 't_cta_0047_02']
        self.user = 'u_cta_0047'
        self.error = 'permission denied for schema public'

    def test_create_table_as(self):
        text = '-----step1:创建用户;expect:成功-----'
        self.log.info(text)
        sql = f"drop user if exists {self.user} cascade;" \
              f"create user {self.user} with password " \
              f"'{macro.COMMON_PASSWD}';"
        res = self.pri_sh.execut_db_sql(sql)
        self.log.info(res)
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, res,
                      '执行失败：' + text)
        self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG, res,
                      '执行失败：' + text)

        text = '-----step2:建源表;expect:成功-----'
        self.log.info(text)
        sql = f'drop table if exists {self.tb_name[0]}; ' \
              f'create table {self.tb_name[0]}(id int);'
        res = self.pri_sh.execut_db_sql(sql)
        self.log.info(res)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, res,
                      '执行失败：' + text)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, res,
                      '执行失败：' + text)

        text = '-----step3:收回用户在当前模式的create权限;expect:成功-----'
        self.log.info(text)
        res = self.pri_sh.execut_db_sql('show current_schema')
        self.log.info(res)
        self.assertNotIn('ERROR', res, '执行失败：' + text)
        schema_name = res.splitlines()[-2].split(',')[-1].strip()
        self.log.info(schema_name)
        sql = f'revoke create on schema {schema_name} from {self.user};'
        res = self.pri_sh.execut_db_sql(sql)
        self.log.info(res)
        self.assertIn(self.constant.REVOKE_SUCCESS_MSG, res,
                      '执行失败：' + text)

        text = '-----step4:赋予用户源表的所有权限;expect:成功-----'
        self.log.info(text)
        sql = f'grant all privileges on table {self.tb_name[0]} to {self.user};'
        res = self.pri_sh.execut_db_sql(sql)
        self.log.info(res)
        self.assertIn(self.constant.GRANT_SUCCESS_MSG, res,
                      '执行失败：' + text)

        text = '-----step5:以新建用户身份进入当前模式，执行create table as;' \
               'expect:报错权限受限-----'
        self.log.info(text)
        sql = f'set current_schema = {schema_name};' \
              f'drop table if exists {self.tb_name[1]};' \
              f'create table {self.tb_name[1]} as select * from {self.tb_name[0]};'
        cmd = f"""source {macro.DB_ENV_PATH};
        gsql -d {self.pri_user.db_name} -p {self.pri_user.db_port} -c "{sql}" -U '{self.user}' -W '{macro.COMMON_PASSWD}'
        """
        res = self.pri_user.sh(cmd).result()
        self.log.info(res)
        self.assertIn(self.constant.SET_SUCCESS_MSG, res,
                      '执行失败：' + text)
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, res,
                      '执行失败：' + text)
        self.assertIn(self.error, res, '执行失败：' + text)

    def tearDown(self):
        text = '-----step6:清理环境;expect:成功-----'
        self.log.info(text)
        sql = f'drop user if exists {self.user} cascade;'
        drop_user_res = self.pri_sh.execut_db_sql(sql)
        self.log.info(drop_user_res)

        for i in self.tb_name:
            sql = f'drop table if exists {i} cascade;'
            drop_table_res = self.pri_sh.execut_db_sql(sql)
            self.log.info(drop_table_res)
            self.assertIn(self.constant.TABLE_DROP_SUCCESS, drop_table_res,
                          '执行失败：' + text)
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, drop_user_res,
                      '执行失败：' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
